package main

import (
	"fmt"
	"io"
	"net/http"
	"regexp"

	//"os"
	"strconv"
)

/*
获取杉果里面游戏排序价格等,评分及评分人数
纵向数据:游戏名称 <a title="游戏名称"
		正则表达式写法:`<a title="(?s:(.*?))"`

		价格 <span class="game-sale-price">价格</span>
		正则表达式写法:`<span class="game-sale-price">(?s:(.*?))</span>`

		发行时间: 发行于xxxx-xx-xx
		正则表达式写法:`发行于(?s:(.*?))·

横向数据(分页):https://www.sonkwo.hk/store/search?page=i  变量为i
*/

func httpGet(url string) (result string, err error) {
	resp, err1 := http.Get(url)
	if err1 != nil {
		err = err1
	}
	defer resp.Body.Close()

	buf := make([]byte, 4096)
	for {
		n, err2 := resp.Body.Read(buf)
		if n == 0 {
			//fmt.Println("读取结束")
			break
		}
		if err2 != nil && err2 != io.EOF {
			err = err2
			return
		}
		result += string(buf[:n])
	}
	return

}

func spiderpage(i int, page chan int) {
	url := "https://www.sonkwo.hk/store/search?page=" + strconv.Itoa(i)

	result, err := httpGet(url)
	if err != nil {
		fmt.Println("获取错误:", err)
		return
	}

	//f, err := os.Create("./result" + strconv.Itoa(i) + ".html")

	// if err != nil {
	// 	fmt.Print("文件创建错误", err)
	// 	return
	//	}

	// f.WriteString(result)
	// f.Close()

	//	str1 := "https://movie.douban.com/top250?start="
	// str2 := "&filter="
	// url := str1 + strconv.Itoa((i-1)*25) + str2
	// fmt.Println(url)
	// result, err := httpGet(url)
	// if err != nil {
	// 	fmt.Println("httpget err", err)
	// 	return
	// }
	//<a title="(?s:(.*?))"
	ret := regexp.MustCompile(` <script type="(?s:(.*?))"`)
	gameNames := ret.FindAllStringSubmatch(result, -1)
	for _, gameName := range gameNames {
		fmt.Println("gameName:", gameName[1])

	}
	page <- i

}

func working(start, end int) {
	page := make(chan int)
	fmt.Printf("正在爬取%d到%d页...\n", start, end)

	for i := start; i <= end; i++ {
		go spiderpage(i, page)
	}

	for i := start; i <= end; i++ {
		fmt.Printf("第%d页已被爬取", <-page)
	}
}

func main() {

	var start, end int

	fmt.Println("请输入起始页:")
	fmt.Scan(&start)
	fmt.Println("请输入终止页:")
	fmt.Scan(&end)

	working(start, end)
}
